package com.zndroid.netmonitor.monitor.impl;

import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.RemoteException;

import androidx.annotation.NonNull;

import com.zndroid.netmonitor.monitor.INetSpeedChangeCallBack;

/**
 * Created by lzy on 2020/12/18.
 *
 * 仍然使用 TrafficStats 而不是 NetworkStatsManager，
 * 因为网速的话核心都是通过 （某个时间段内的流量/时间段） 计算得来的，只是换了不同API而已
 * 新版本（API>=24）的需要额外权限{@link android.Manifest.permission#PACKAGE_USAGE_STATS}支持
 * 综合考虑仍然选择 TrafficStats 实现，如果哪天弃用 TrafficStats，再使用 NetworkStatsManager
 */
@TargetApi(Build.VERSION_CODES.N)
public class MonitorSpeedImplAPI24 extends MonitorSpeedImpl {

    public MonitorSpeedImplAPI24(int periodSeconds, @NonNull INetSpeedChangeCallBack speedChangeCallBack) {
        super(periodSeconds, speedChangeCallBack);
    }

    @Override
    public void startMonitorSpeed(@NonNull Context context) {
        super.startMonitorSpeed(context);
    }

    @Override
    public void stopMonitorSpeed(@NonNull Context context) {
        super.stopMonitorSpeed(context);
    }

    private void bucket(@NonNull Context context) {
        NetworkStatsManager networkStatsManager = (NetworkStatsManager) context.getSystemService(Context.NETWORK_STATS_SERVICE);
        if (!hasPermissionToReadNetworkStats(context)) {
            throw new SecurityException("Network stats history is forbidden，call 'Settings.ACTION_USAGE_ACCESS_SETTINGS' at first pls");
        }
        try {
            NetworkStats.Bucket bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE | ConnectivityManager.TYPE_WIFI, "", 0, System.currentTimeMillis());
            double total = bucket.getTxBytes() + bucket.getRxBytes();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private boolean hasPermissionToReadNetworkStats(@NonNull Context context) {
        final AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            mode = appOps.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), context.getPackageName());
        } else {
            mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), context.getPackageName());
        }

        return mode == AppOpsManager.MODE_ALLOWED;
    }
}
